package com.example.financialsystem.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.financialsystem.ModifyRecordActivity;
import com.example.financialsystem.R;
import com.example.financialsystem.custom.MyListView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import models.FlowStatistic;
import models.Record;

import static com.example.financialsystem.application.MyApplication.getContext;
import static others.Const.currentUserVo;
import static others.Tools.ToastShow;
import static others.Tools.string2Calendar;

public class FlowsAdapter extends RecyclerView.Adapter<FlowsAdapter.ViewHolder> {

    private List<FlowStatistic> mDataList;
    private Context context;

    static class ViewHolder extends RecyclerView.ViewHolder{
        private TextView bigTitle;
        private TextView smallTile;
        private TextView income;
        private TextView outcome;
        private TextView surplus;
        private MyListView recordListView;
        private TextView notRecordText;

        public ViewHolder(View view){
            super(view);
            bigTitle = (TextView)view.findViewById(R.id.recycler_title_big);
            smallTile = (TextView)view.findViewById(R.id.recycler_title_small);
            income = (TextView)view.findViewById(R.id.recycler_title_income);
            outcome = (TextView)view.findViewById(R.id.recycler_title_outcome);
            surplus = (TextView)view.findViewById(R.id.recycler_title_surplus);
            recordListView = (MyListView)view.findViewById(R.id.recycler_details_listView);
            notRecordText = (TextView)view.findViewById(R.id.not_record);
        }
    }

    public FlowsAdapter(List<FlowStatistic> classification_records){
        mDataList = classification_records;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recycler_details_statistic,parent,false);
        context = view.getContext();
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        FlowStatistic data = mDataList.get(position);
        double income = data.getStatisticInfo().getIncome();
        double outcome = data.getStatisticInfo().getOutcome();
        holder.income.setText(income+"");
        holder.outcome.setText(outcome+"");
        holder.surplus.setText(income - outcome+"");
        setTitle(holder,string2Calendar(data.getStatisticInfo().getName()),
                data.getStatisticInfo().getType(),Integer.valueOf(data.getStatisticInfo().getRemark()));

        //配置listView
        List<Record> records = data.getRecords();
        if (records!=null) {
            RecordAdapter adapter = new RecordAdapter(getContext(), R.layout.item_record, records);
            holder.recordListView.setAdapter(adapter);
            setListViewHeight(holder.recordListView);
            holder.recordListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Record record = records.get(position);
                    if (record.getUserid().equals(currentUserVo.getId())){
                        Intent intent = new Intent(getContext(), ModifyRecordActivity.class);
                        intent.putExtra("record",record);
                        context.startActivity(intent);
                        Activity activity = (Activity)context;
                        activity.finish();
                    } else {
                        ToastShow("该流水记录您无权修改");
                    }
                }
            });
            holder.notRecordText.setVisibility(View.GONE);
        } else {
            holder.recordListView.setVisibility(View.GONE);
            holder.notRecordText.setVisibility(View.VISIBLE);
        }


    }

    private void setTitle(ViewHolder holder,Calendar date, int type,int numOfWeeks){
        int year = date.get(Calendar.YEAR);
        int month = date.get(Calendar.MONTH)+1;
        int day = date.get(Calendar.DATE);
        switch (type){
            case 0:
            case 1:
                holder.bigTitle.setText(day+"日");
                holder.smallTile.setText(month+"月"+year+"年");
                break;
            case 2:
                holder.bigTitle.setText("第"+(getItemCount()-numOfWeeks)+"周");
                holder.smallTile.setText(getWeekStart(date)+"-"+getWeekEnd(date));
                break;
            case 3:
                holder.bigTitle.setText(month+"月");
                holder.smallTile.setText(year+"年");
                break;
        }
    }

    public String getWeekStart(Calendar calendar){
        int day_of_week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (day_of_week == 0) day_of_week = 7;
        calendar.add(Calendar.DATE, -day_of_week + 1);
        SimpleDateFormat sdf= new SimpleDateFormat("yy-MM-dd");
        return sdf.format(calendar.getTime());
    }

    public String getWeekEnd(Calendar calendar){
        int day_of_week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (day_of_week == 0)
            day_of_week = 7;
        calendar.add(Calendar.DATE, -day_of_week + 7);
        SimpleDateFormat sdf= new SimpleDateFormat("yy-MM-dd");
        return sdf.format(calendar.getTime());
    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    public void setListViewHeight(ListView listView) {
        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            //listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            //获得每个子item的视图
            listItem.measure(0, 0);
            //先判断写入的widthMeasureSpec和heightMeasureSpec是否和当前的值相等
            // 如果不等，重新调用onMeasure()，计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight();   //统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight +
                (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        //加上每个item之间的距离，listView.getDividerHeight()获取子项间分隔符占用的高度
        listView.setLayoutParams(params);
        //params.height最后得到整个ListView完整显示需要的高度
    }
}
